package com.example.project.controller;

import com.example.framework.baseService.TokenService;
import com.example.framework.config.token.UserLoginToken;
import com.example.project.entity.UserInfoBean;
import com.example.project.service.LoginService;
import com.example.utils.resultFormat.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/loginController")
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    TokenService tokenService;

    //登录
    @PostMapping("/login")
//    public Result login(@RequestBody UserInfoBean user , HttpServletRequest request, ServletResponse response){
    public Result login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        Model model, HttpServletRequest request, ServletResponse response){
        UserInfoBean user = new UserInfoBean();
        user.setUserName(userName);
        user.setPassword(password);
        Result loginInfo =  loginService.login(user,request,response);
        return loginInfo;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserInfoBean user) {
        return loginService.addUser(user);
    }

    /**
     * 退出登录
     * @param user
     * @return
     */
    @GetMapping("/exitLogin")
    public void exitLogin(@RequestBody UserInfoBean user) {
         loginService.exitLogin(user);
    }

    /**
     * 不加注解的话默认不验证，登录接口一般是不验证的。
     在getMessage()中我加上了登录注解，说明该接口必须登录获取token后，
     在请求头中加上token并通过验证才可以访问
     *
     * @return
     *
     * 拦截所有请求，通过判断是否有@LoginRequired注解 决定是否需要登录
     */
    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }
}
